package Controlador;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.StringTokenizer;

import javax.swing.*;

import Vista.*;

public class Abrir extends AbstractAction{

	
	private static final long serialVersionUID = 1L;
	private File fichero;
	private Ventana ventana; 
	
	public Abrir (Ventana c)
	{
		this.ventana=c;
	}
	
	@Override
	public void actionPerformed(ActionEvent e){
		
		JFrame f=new JFrame();
		ventana.miSetVisible(true);
		ventana.borrarTexto();
		
		
		JFileChooser abrirFicheros=new JFileChooser();
		int opc=abrirFicheros.showOpenDialog(f);
		
		if(opc==JFileChooser.APPROVE_OPTION)
		{
			fichero=abrirFicheros.getSelectedFile();
			
		}
		else if(opc==JFileChooser.CANCEL_OPTION)
		{
			 System.out.println("Cancel was selected");
		}
		BufferedReader leer=null;
		try {
			StringTokenizer to=new StringTokenizer(fichero.toString(),".");
			String aux="";
			while(to.hasMoreTokens())
			{
				aux=to.nextToken();
			}
			if(aux.equalsIgnoreCase("txt"))
			{
				leer=new BufferedReader(new FileReader(fichero));
				String leo;
				while((leo=leer.readLine())!= null)
				{
					ventana.setTexto(leo+"\n");
				}
			}
			else
			{
				JOptionPane.showMessageDialog(null, "error, has abierto un " +
						"archivo que no es txt", "menaje de error", JOptionPane.INFORMATION_MESSAGE);

			}
				
		}
		catch (NullPointerException e1) {
			
			System.out.println("NullPointerException");
		}
		catch (IOException e2) {
			
			System.out.println("IOException");
		}
		finally
		{
			try{
				leer.close();
			}
			catch(FileNotFoundException fnfe){
				System.out.println("el fichero no se ha podido cerrar");	
			} catch (IOException e1) {
				
				System.out.println("IOException");
			}
			catch (NullPointerException e1) {
				
				System.out.println("NullPointerException");
			}
		}
		
	}

}
